package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;

import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@Transactional
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    private ApArticleMapper articlemapper;
    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private ApArticleContentMapper contentMapper;
    @Autowired
    private CacheService cacheService;
private final static Short MAX_PAGE_SIZE=50;
    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //先判断一下条件dto中没有参数:代表首页,有参数:可能是用户转换频道或者向下向上刷新
        //1.校验size,校验频道,校验时间
        if (dto.getSize() == 0 || dto.getSize() == null) {
            //设置一个默认值
            dto.setSize(10);
        }//因为分页有一个上限,我们给他设定成50.又因为50是个固定值,抽成静态常量
        int size = Math.min(dto.getSize(), MAX_PAGE_SIZE);
        dto.setSize(size);//设置默认的size就是10-50
        //判断type 1 :加载更多  2:加载最新 默认设置成加载更多
        if (!loadtype.equals(1)&&!loadtype.equals(2)){
          loadtype= ArticleConstants.LOADTYPE_LOAD_MORE;
        }//判断频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);//设置成默认的频道模式
        }//时间校验
        if (dto.getMaxBehotTime()==null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        //将查询条件放入mapper中,mapper中根据传入的条件进行查询.但是可能这两个参数都没有值,我们就要给他设置默认值.
        List<ApArticle> apArticleList = articlemapper.loadArticleList(dto, loadtype);
        return ResponseResult.okResult(apArticleList);
    }

    /**
     * 保存发布的文章到用户端
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
          //1.校验dto
        if (null==dto||StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.判断dto中的id是否存在,不存在就是新增,存在就是修改操作
        //2.1新增
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        if (null==dto.getId()){
            //1.保存文章
          this.save(apArticle);//因为dto继承了aparticle,所以直接拷贝属性就可以了
            //2.保存文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsForward(true);
            apArticleConfig.setIsDelete(false);
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDown(false);
            configMapper.insert(apArticleConfig);
            //3.保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            contentMapper.insert(apArticleContent);
        }else {
        //2.2修改操作
         //1.修改文章中的信息
        this.updateById(apArticle);
        //2.修改文章中的内容(因为文章的配置在之前已经设置过了,所以不用修改了)
       //不能new对象了,要查找出这个对象的内容 ApArticleContent apArticleContent = new ApArticleContent();
        ApArticleContent apArticleContent = contentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
        apArticleContent.setContent(dto.getContent());
        contentMapper.updateById(apArticleContent);
        //发布文章成功,自动添加索引库到es中
            createArticleESIndex(apArticle,apArticleContent.getContent());
        }
        return ResponseResult.okResult(apArticle.getId());
    }
    /**
     * 加载文章列表
     * @param dto
     * @param type  1 加载更多   2 加载最新
     * @param firstPage  true 是首页  false 不是首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if (firstPage){
            String json = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(json)){
                List<HotArticleVo> hotArticleVos = JSON.parseArray(json, HotArticleVo.class);
                return ResponseResult.okResult(hotArticleVos);
            }
        }
        return load(type,dto);
    }
    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //计算文章分值
        Integer score = computeScore(apArticle);
        score=score*3;
        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);


    }

    /**
     * 将redis中的数据进行替换或者更改
     * @param apArticle
     * @param score
     * @param key
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String key) {
        String channelvalue = cacheService.get(key);
        if (StringUtils.isNotBlank(channelvalue)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(channelvalue, HotArticleVo.class);
            boolean flag = true;
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {//这一步代表当前java频道中有我点赞了的文章,只用修改分数即可
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }//如果有这篇文章走上面,flag=false就不会走下面
            if (flag) {//判断集合中分数最小的集合和当前文章的分数进行比较
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo minscorearticle = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (minscorearticle.getScore() < score) {
                        hotArticleVoList.remove(minscorearticle);
                        HotArticleVo hotArticleVo = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hotArticleVo);
                        hotArticleVo.setScore(score);
                        hotArticleVoList.add(hotArticleVo);
                    }
                } else {//里面参数没达到30条,直接添加进去
                    HotArticleVo hotArticleVo = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hotArticleVo);
                    hotArticleVo.setScore(score);
                }
            }
            //缓存到redis,先排序
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(key,JSON.toJSONString(hotArticleVoList));
        }
    }
    /**
     * 修改数据库文章中的点赞数
     * @param mess
     * @return
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle article = this.getById(mess.getArticleId());
        article.setCollection(article.getCollection()==null?0:article.getCollection()+mess.getCollect());
        article.setComment(article.getComment()==null?0:article.getComment()+mess.getComment());
        article.setLikes(article.getLikes()==null?0:article.getLikes()+mess.getLike());
        article.setViews(article.getViews()==null?0:article.getViews()+mess.getView());
        this.updateById(article);
        return article;
    }

    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 添加索引库
     * @param apArticle
     * @param content
     */
    private void createArticleESIndex(ApArticle apArticle, String content) {
        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,searchArticleVo);
        searchArticleVo.setContent(content);
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
    }
    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }

}
